package com.googlecode.webduff.authentication.provider;

import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.googlecode.webduff.WebDuffConfiguration;
import com.googlecode.webduff.WebdavStatus;
import com.googlecode.webduff.exceptions.MethodResponseError;

import sun.misc.BASE64Decoder;

public class BasicWebdavAuthenticationProvider implements WebdavAuthenticationProvider {
	
	private String theRealm;
	
	public void init(WebDuffConfiguration config) {
		theRealm = config.getConf().getString("realm");
	}
	
	public BasicCredential getCredential(HttpServletRequest request, HttpServletResponse response) throws MethodResponseError {
		response.addHeader("WWW-Authenticate", "Basic realm=\"" + theRealm + "\"");
		
		String authorizationHeader = request.getHeader("Authorization");

		if(authorizationHeader != null && authorizationHeader.toUpperCase().startsWith("BASIC ")) {
			String encoded = authorizationHeader.substring(6);
			BASE64Decoder decoder = new sun.misc.BASE64Decoder();
	        try {
				String[] decoded = new String(decoder.decodeBuffer(encoded)).split(":");
				return new BasicCredential(decoded[0], decoded[1]);
			} catch (IOException e) {}
		}
		
		throw new MethodResponseError(WebdavStatus.SC_UNAUTHORIZED);
	}

}